package com.tfleo.mealssenger;

import java.util.ArrayList;

import com.tfleo.mealssenger.R;
import com.tfleo.mealssenger.adapter.WebGalleryAdapter;
import com.tfleo.mealssenger.object.Food;
import com.tfleo.mealssenger.utility.DataFetcher;
import com.tfleo.mealssenger.widget.SlowMotionGallery;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.Toast;

public class GalleryActivity extends Activity {
	private String mProvider = LocationManager.GPS_PROVIDER;
	private LocationManager mLocationManager;
	private LocationListener mLocationListener;
	private Location mLocation;
	
	private Button vSuggestionButton;
	
	private SharedPreferences mSharedPref;
	private SharedPreferences.Editor mPrefEditor;

	private LayoutInflater mInflater;
	private Context mContext;

	private ArrayList<Food> mFoods;

	private WebGalleryAdapter mWebGalleryAdapter;

	public boolean first = true;
	private int mUserId;
	private SlowMotionGallery vGallery;
	private String mAuth;
	private String mFilterBy;
	private boolean isFiltered = false;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gallery_layout);
		mAuth = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID); //for authentication
		//get main view
		//vFocusedImg = (RemoteImageView) findViewById(R.id.img);
		//vFoodName = (TextView) findViewById(R.id.name);
		//vFoodLocation = (TextView) findViewById(R.id.location);
		mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		mContext = this;
		mSharedPref = getSharedPreferences(Main.USER_DATA, MODE_PRIVATE);
		mPrefEditor = mSharedPref.edit();
		mUserId = mSharedPref.getInt(Main.USER_ID, 0);

		mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
		if(!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			mProvider = LocationManager.NETWORK_PROVIDER;
			//Toast.makeText(getApplicationContext(), "Switching provider", Toast.LENGTH_SHORT).show();
		}
		mLocationListener = new MyLocationListener();
		//mLocation = mLocationManager.getLastKnownLocation(mProvider);
		mLocationManager.requestSingleUpdate(mProvider, mLocationListener, null);

		vGallery = (SlowMotionGallery) findViewById(R.id.gallery_list);
		vSuggestionButton = (Button) findViewById(R.id.suggestion_btn);
		vSuggestionButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent i = new Intent(mContext, SuggestionActivity.class);
				startActivity(i);
			}
			
		});
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if(mWebGalleryAdapter != null) {
			mWebGalleryAdapter.notifyDataSetChanged();
		}
	}
	
	private class FetchFoodTask extends AsyncTask<Double, Void, Boolean> {
		private ProgressDialog mProgressDialog;

		@Override    
		protected void onPreExecute() {       
			super.onPreExecute();
			mProgressDialog = new ProgressDialog(mContext);
			mProgressDialog.setMessage("Loading...");
			mProgressDialog.setCancelable(false);
			mProgressDialog.setIndeterminate(true);
			mProgressDialog.show();
		}

		@Override
		protected Boolean doInBackground(Double... point) {

			mFoods = DataFetcher.fetchRecommendation(mUserId, point[0], point[1], mAuth, isFiltered, mFilterBy);
			if(mFoods == null) {
				return false;
			}

			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {

				mWebGalleryAdapter = new WebGalleryAdapter(mContext, mFoods, mInflater);

				vGallery.setAdapter(mWebGalleryAdapter);
				vGallery.setCallbackDuringFling(false);
				vGallery.setSpacing(-1);
				
				vGallery.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						Food food = mFoods.get(position);	
						if(food.id == 0) {
							Toast.makeText(mContext, "No food around here!", Toast.LENGTH_SHORT).show();
							return;
						}
						Intent i = new Intent(mContext, FoodActivity.class);
						i.putExtra("id", food.id);
						i.putExtra("name", food.name); 
						i.putExtra("location_id", food.locationId);
						i.putExtra("location_name", food.locationName);
						i.putExtra("description", food.description);
						i.putExtra("category", food.category);
						i.putExtra("image", food.imageUrl);
						i.putExtra("likes", food.numEaten);
						i.putExtra("rating", food.rating);
						startActivity(i); 
					}
				});
				vSuggestionButton.setVisibility(View.VISIBLE);
				mProgressDialog.dismiss();
			} else {
				Toast.makeText(mContext, "Error: Connection with server failed!", Toast.LENGTH_SHORT).show();
				mProgressDialog.dismiss();
			}
		}
	}


	public class MyLocationListener implements LocationListener {
		public void onLocationChanged(Location location) {
			if(location != null) {
				mLocation = location;

				FetchFoodTask task = new FetchFoodTask();
				task.execute(mLocation.getLongitude(), mLocation.getLatitude());
				
				mPrefEditor.putFloat(Main.LAST_LONGITUDE, (float) mLocation.getLongitude());
				mPrefEditor.putFloat(Main.LAST_LATITUDE, (float) mLocation.getLatitude());
				mPrefEditor.commit();
			}
		}

		public void onProviderDisabled(String provider) {
			mProvider = (provider == LocationManager.GPS_PROVIDER) ?
					LocationManager.NETWORK_PROVIDER : LocationManager.GPS_PROVIDER;
			Toast.makeText(getApplicationContext(), "Switching provider...", Toast.LENGTH_SHORT).show();
		}

		public void onProviderEnabled(String provider) {
			mProvider = (provider == LocationManager.GPS_PROVIDER) ?
					LocationManager.GPS_PROVIDER : LocationManager.NETWORK_PROVIDER;
			Toast.makeText(getApplicationContext(), "Switching provider...", Toast.LENGTH_SHORT).show();
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			if(status != LocationProvider.AVAILABLE) {
				mProvider = (provider == LocationManager.GPS_PROVIDER) ?
						LocationManager.NETWORK_PROVIDER : LocationManager.GPS_PROVIDER;
			}
			Toast.makeText(getApplicationContext(), "Switching provider...", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.gallery_menu, menu);
		return result;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent i;
		switch(item.getItemId()) {
		case R.id.category:
			//onSearchRequested();
			final CharSequence[] items = {"None", "Chinese", "French", "Indian", "Indo/Malay", "Italian", "Japanese", 
					"Korean", "Mexican", "Middle Eastern", "Other", "Peranakan", "Thai", "Vietnamese", "Western"};

	        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
	        builder.setTitle("Sort by...");
	        builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int item) {
	                //Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
	            	mFilterBy = (String) items[item];
	            	if(item == 0) {
	            		isFiltered = false;
	            	} else {
	            		isFiltered = true;
	            	}
	            }
	        });
	        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int id) {
	            	FetchFoodTask task = new FetchFoodTask();
	    			task.execute(mLocation.getLongitude(), mLocation.getLatitude());
	                dialog.dismiss();
	            }
	        });
	        
	        AlertDialog alert = builder.create();
	        alert.show();
			return true;
		case R.id.refresh:
			FetchFoodTask task = new FetchFoodTask();
			task.execute(mLocation.getLongitude(), mLocation.getLatitude());
			return true;
		case R.id.search:
			onSearchRequested();
			return true;
		case R.id.preferences:
			showSettings();
			return true;
		case R.id.info:
			showInfo();
			return true;
		case R.id.logout:
			i = new Intent(this, LoginActivity.class);
			i.putExtra("logout", true);
			startActivity(i);
			finish();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	/**
	 * Start SettingsActivity.
	 */
	private void showSettings() {
		Intent i = new Intent(this, SettingsActivity.class);
		startActivity(i);
	}

	/**
	 * Start InfoActivity.
	 */
	private void showInfo() {
		Intent i = new Intent(this, InfoActivity.class);
		startActivity(i);
	}
}
